var moment = require('moment');
var db = require('../config/mongo_database');
var secret = require('../config/secret');
var redisClient = require('../config/redis_database').redisClient;
var tokenManager = require('../config/token_manager');

// 查询
exports.queryList = function(req, res){
	var name = req.body.name || '';
	var codes = req.body.codes || '';
	var type = req.body.type || '';
	var type1 = req.body.type1 || '';
	var hot = req.body.hot || '';
	var pages = req.body.pages || 0;
	var where = {status:'1'};

	if(name!='') where.name = name;
	if(codes!='') where.codes = codes;
	if(type!='') where.type = type;
	if(type1!='') where.type1 = type1;
	if(hot!='') where.hot = hot;

	console.log(where)
	db.postModel.count(where, function(err, count){
		console.log(err, count)
		db.postModel
		.where(where)
		.skip(pages*12)
		.limit(12)
		.sort({'updated':-1})
		.exec(function(err, list){
			res.json({count:count, list:list});
		})
	});
}

// 修改
exports.updatePost = function(req, res){
	var data = req.body;
	var updateObj = {};
	toDBObject(2, updateObj, data);

	db.postModel.update({pid:data.pid}, {$set:updateObj}, function(err){
		console.log(err)
		if(err) return res.sendStatus(500)
		return res.sendStatus(200)
	})
	
}

exports.addPost = function(req, res){
	var post = new db.postModel();
	var data =  req.body;
	toDBObject(1, post, data);

	post.save(function(err){
		console.log(err)
		if(err) return res.json({status:500, msg:"保存失败，商品编号重复"});
		return res.json({status:200, msg:"保存成功"});
	})
}

// 转成数据库对象
function toDBObject(type, newOb, oldOb){
	if(type==1){
		newOb.pid =  moment(new Date()).format("HHmmss");
	}
	newOb.name     = oldOb.name;
	newOb.codes    = oldOb.codes;
	newOb.oldprice = oldOb.oldprice;
	newOb.price    = oldOb.price;
	newOb.yprice   = oldOb.yprice;
	newOb.shcema   = oldOb.shcema;
	newOb.size     = JSON.parse(oldOb.size);
	newOb.issize   = oldOb.issize;
	newOb.type     = oldOb.type;
	newOb.type1    = oldOb.type1;
	newOb.tag      = oldOb.tag;
	newOb.tagimg   = oldOb.tagimg;
	newOb.hot      = oldOb.hot;
	newOb.version  = oldOb.version;
	newOb.demo     = oldOb.demo;
	newOb.download = oldOb.download;
	newOb.credate  = oldOb.credate;
	newOb.modate   = oldOb.modate;
	newOb.title    = oldOb.title;
	// oldOb.imgs = oldOb.imgs.replace(/\n/g, "");
	// newOb.imgs = oldOb.imgs.split(";");
	newOb.imgs     = JSON.parse(oldOb.imgs);
	newOb.codeyuan = oldOb.codeyuan;
	newOb.postlog  = oldOb.postlog;
	newOb.details  = JSON.parse(oldOb.details);
	newOb.desc     = oldOb.desc;
	newOb.stauts   = oldOb.stauts;
	newOb.updated  = new Date();
}